package gui;

import java.util.HashMap;
import java.util.Map;

import com.mxgraph.io.mxStylesheetCodec;
import com.mxgraph.model.mxCell;
import com.mxgraph.model.mxGraphModel;
import com.mxgraph.util.mxConstants;
import com.mxgraph.util.mxEvent;
import com.mxgraph.util.mxEventObject;
import com.mxgraph.util.mxEventSource.mxIEventListener;
import com.mxgraph.view.mxGraph;

import core.Unit;
import core.UnitConnection;

public class GraphListener implements mxIEventListener {
	private mxGraph graph;
	public GraphListener(mxGraph graph) {
		this.graph = graph;
	}
	@Override
	public void invoke(Object sender, mxEventObject evt) {
		if(evt.getName().equals(mxEvent.CELLS_ADDED)){
			Object[] cells = (Object[]) evt.getProperty("cells");
			for(Object cell:cells){
				mxCell mxc= (mxCell)cell;
				if(mxc.isEdge()){
					if(evt.getProperty("absolute").toString().equals("true")){
						break;
					}
					
					String tPort = mxc.getTarget().getValue().toString();
					String sPort = mxc.getSource().getValue().toString();
					
					Unit tUnit = (Unit) mxc.getTarget().getParent().getValue();
					Unit sUnit = (Unit) mxc.getSource().getParent().getValue();
					
					UnitConnection uc = new UnitConnection(sUnit, sPort, tUnit, tPort);
					mxc.setValue(uc);
					sUnit.connect(uc);
					
				}
			}
		
		}else if(evt.getName().equals(mxEvent.CELLS_REMOVED)){
			Object[] cells = (Object[]) evt.getProperty("cells");
			for(Object cell:cells){
				mxCell mxc= (mxCell)cell;
				if(mxc.isEdge()){
					Unit sunit = (Unit) mxc.getSource().getParent().getValue();
					sunit.disconnect((UnitConnection)mxc.getValue());
				}
			}
		
		}else{
			mxCell prev = (mxCell) evt.getProperty("previous");
			if(prev != null){
				mxCell term = (mxCell) evt.getProperty("terminal");
				mxCell edge = (mxCell) evt.getProperty("edge");
				UnitConnection uc = (UnitConnection) edge.getValue();
				uc.getSource().disconnect(uc);
				mxGraphModel gm = (mxGraphModel)(graph.getModel());
				if((Boolean)evt.getProperty("source")){
					String sPort = edge.getSource().getValue().toString();
					uc = new UnitConnection((Unit) term.getParent().getValue(), sPort, uc.getTarget(), uc.getTPort());
				}else{
					String tPort = edge.getTarget().getValue().toString();
					uc = new UnitConnection(uc.getSource(), uc.getSPort(), (Unit) term.getParent().getValue(), tPort);
				}
				edge.setValue(uc);
				uc.getSource().connect(uc);
			}
			
		}	
	}
}

